import { defineStore } from 'pinia'
import { ref, watch } from 'vue'

interface HSL {
    h: number
    s: number
    l: number
}

export const useThemeStore = defineStore('theme', () => {
    // 调整为与图片中按钮相同的蓝色 #409EFF
    const primaryColor = ref(localStorage.getItem('theme-primary-color') || '#409EFF')

    // 优化后的 HEX 转 HSL（支持简写格式）
    const hexToHSL = (hex: string): HSL => {
        // 扩展简写颜色代码（如 #fff → #ffffff）
        const fullHex = hex.length === 4 ?
            `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}` : hex

        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(fullHex)
        if (!result) return { h: 0, s: 0, l: 0 }

        const parse = (s: string) => parseInt(s, 16) / 255
        const r = parse(result[1])
        const g = parse(result[2])
        const b = parse(result[3])

        const max = Math.max(r, g, b)
        const min = Math.min(r, g, b)
        let h = 0, s = 0, l = (max + min) / 2

        if (max !== min) {
            const d = max - min
            s = l > 0.5 ? d / (2 - max - min) : d / (max + min)
            switch (max) {
                case r: h = (g - b) / d + (g < b ? 6 : 0); break
                case g: h = (b - r) / d + 2; break
                case b: h = (r - g) / d + 4; break
            }
            h /= 6
        }

        return {
            h: Math.round(h * 360),
            s: Math.round(s * 100),
            l: Math.round(l * 100)
        }
    }

    // 保持原有 HSL 转 HEX 方法
    const hslToHEX = (hsl: HSL): string => {
        const h = hsl.h / 360
        const s = hsl.s / 100
        const l = hsl.l / 100

        let r, g, b

        if (s === 0) {
            r = g = b = l
        } else {
            const hue2rgb = (p: number, q: number, t: number) => {
                if (t < 0) t += 1
                if (t > 1) t -= 1
                if (t < 1/6) return p + (q - p) * 6 * t
                if (t < 1/2) return q
                if (t < 2/3) return p + (q - p) * (2/3 - t) * 6
                return p
            }

            const q = l < 0.5 ? l * (1 + s) : l + s - l * s
            const p = 2 * l - q
            r = hue2rgb(p, q, h + 1/3)
            g = hue2rgb(p, q, h)
            b = hue2rgb(p, q, h - 1/3)
        }

        const toHex = (x: number) => {
            const hex = Math.round(x * 255).toString(16)
            return hex.length === 1 ? '0' + hex : hex
        }

        return `#${toHex(r)}${toHex(g)}${toHex(b)}`
    }

    // 优化颜色变体生成算法
    const generateVariant = (baseHex: string, lightDelta: number): string => {
        const baseHSL = hexToHSL(baseHex)

        // 调整饱和度计算（防止颜色过白）
        const minSaturation = 15 // 最小饱和度阈值
        const saturation = Math.max(minSaturation, baseHSL.s - lightDelta * 0.3)

        // 非线性亮度调整（在较亮区间减小增量）
        const adjustedDelta = lightDelta * (baseHSL.l < 50 ? 1 : 0.8)
        const newLightness = Math.min(95, baseHSL.l + adjustedDelta) // 限制最大亮度

        return hslToHEX({
            h: baseHSL.h,
            s: saturation,
            l: newLightness
        })
    }

    // 更新 CSS 变量（匹配图片中的色阶）
    const updateCssVariables = (color: string) => {
        const el = document.documentElement
        el.style.setProperty('--el-color-primary', color)

        // 调整后的色阶（保持蓝色调可见性）
        el.style.setProperty('--el-color-primary-light-3', generateVariant(color, 15)) // 用于按钮悬停
        el.style.setProperty('--el-color-primary-light-5', generateVariant(color, 25)) // 用于次级文本
        el.style.setProperty('--el-color-primary-light-7', generateVariant(color, 35)) // 用于背景高亮
        el.style.setProperty('--el-color-primary-light-8', generateVariant(color, 40)) // 表格行背景
        el.style.setProperty('--el-color-primary-light-9', generateVariant(color, 45)) // 最浅背景
        el.style.setProperty('--el-color-primary-dark-2', generateVariant(color, -15)) // 按钮激活状态
    }

    const setPrimaryColor = (color: string) => {
        primaryColor.value = color
        localStorage.setItem('theme-primary-color', color)
        updateCssVariables(color)
    }

    // 初始化应用
    updateCssVariables(primaryColor.value)
    watch(primaryColor, updateCssVariables)

    return { primaryColor, setPrimaryColor }
})